package se.webbzon.oschi01.worldeditor;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class WorldAreaWriter {
	
	/*============================================================
	Public Methods
	============================================================*/
	
	/** Writes a world area blueprint to an output stream. **/
	public void write(OutputStream outputStream, WorldAreaBlueprint blueprint) throws IOException {
		writeWorldAreaBlueprint(blueprint,new DataOutputStream(outputStream));
	}
	
	/** Writes a world area blueprint to a given url. **/
	public void write(URL url, WorldAreaBlueprint blueprint) throws IOException {
		URLConnection connection = url.openConnection();
		OutputStream outputStream = connection.getOutputStream();
		write(outputStream,blueprint);
		outputStream.close();
	}
	
	/*============================================================
	Private Methods
	============================================================*/
	
	/** Writes a world area blueprint to a given data output stream. **/
	private void writeWorldAreaBlueprint(	WorldAreaBlueprint blueprint, 
											DataOutputStream dos) throws IOException {
		dos.write(new byte[] {'p', 'i', '3', 'e'});
		dos.writeInt(blueprint.getVersion());
		dos.writeShort(blueprint.getContextName().length());
		dos.writeInt(blueprint.getBlueprints().length);
		dos.writeInt(blueprint.getWorldAreaProperties());
		dos.write(blueprint.getContextName().getBytes("UTF-8"));
		writeWorldObjectBlueprints(blueprint.getBlueprints(),dos);
	}
	
	/** Writes an array of world object blueprint to a given data output stream. **/
	private void writeWorldObjectBlueprints(WorldObjectBlueprint[] blueprints,
											DataOutputStream dos) throws IOException {
		for (WorldObjectBlueprint blueprint : blueprints) {
			// Retrieve the data of the object
			final byte[] data = blueprint.getDeflationData();
			final int[] dependencies = blueprint.getDependencies();
			
			// Write header
			dos.writeInt(blueprint.getDeflationProperties());
			
			if (dependencies == null)
				dos.writeInt(0);
			else
				dos.writeInt(dependencies.length);
			
			dos.writeShort(blueprint.getName().length());
			
			if (data == null)
				dos.writeInt(0);
			else
				dos.writeInt(blueprint.getDeflationData().length);

			if (dependencies != null)
				for (int dependency : dependencies)
					dos.writeInt(dependency);
			
			// Write the name
			dos.write(blueprint.getName().getBytes("UTF-8"));
			
			// Write the data
			if (data != null)
				dos.write(data);
		}
	}

}
